package cn.ac.iie.di.ban.ycl.cleaner.sender;

import cn.ac.iie.di.datadock.rdata.exchange.client.core.REFieldType;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.REMessage;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.log4j.Logger;

/**
 * Created by Black-Laptop on 7/11/2017.
 */
public class PrintScreen {

	public static Logger LOG = Logger.getLogger(PrintScreen.class);
	public static Logger DEFAULT_LOG = Logger.getLogger("R");
	static final Logger datacheckLog = Logger.getLogger("datacheck_log");
	private ArrayBlockingQueue<REMessage> queue;

	public PrintScreen() {
//        DEFAULT_LOG.info("Ready to print...");
//        this.queue = queue;
	}

	public void run(REMessage message) {
		//            REMessage message = queue.take();
		if (message != null) {

			DEFAULT_LOG.info("get " + message.data.size() + " messages.");
			printColumnAndType(message);
			printColumnAndData(message);

		}
	}

	private void printColumnAndType(REMessage message) {
		Object[] columns = message.colNames;
		Object[] types = message.types;
		StringBuilder sb = new StringBuilder();
		sb.append(" {");
		for (int i = 0; i < columns.length; i++) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append(columns[i] + ":" + types[i]);
		}
		sb.append("}");
		datacheckLog.info(sb.toString());
	}

	private void printColumnAndData(REMessage message) {
		Object[] columns = message.colNames;
		Object[] types = message.types;
		for (Object[] data : message.data) {
			printSinaleColumnAndData(columns, types, data);
		}
	}

	private void printSinaleColumnAndData(Object[] columns, Object[] types, Object[] data) {
		StringBuilder sb = new StringBuilder();
		sb.append(" {");
		for (int i = 0; i < columns.length; i++) {
			if (i > 0) {
				sb.append(",");
			}
			if (types[i].equals(REFieldType.Strings)) {
				sb.append("\"" + columns[i] + "\":\"" + Arrays.toString((String[]) data[i]) + "\"");
			} else if (types[i].equals(REFieldType.Structs)) {
				sb.append("\"" + columns[i] + "\":\"" + Arrays.toString((Map[]) data[i]) + "\"");
			} else if (types[i].equals(REFieldType.Ints) || types[i].equals(REFieldType.Longs)) {
				sb.append("\"" + columns[i] + "\":\"" + Arrays.toString((Object[]) data[i]) + "\"");
			} else {
				sb.append("\"" + columns[i] + "\":\"" + data[i] + "\"");
			}
		}
		sb.append("}");
		datacheckLog.info(sb.toString());
	}
}
